package com.handler.http.message.verify;

import com.handler.http.message.constants.Constant;
import com.handler.http.message.enums.RequestEnum;
import com.handler.http.message.handler.ServerException;
import com.handler.http.message.util.sign.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author guoQ.z
 * @date 2021/1/13 11:00
 * TODO
 */
@Slf4j
public class VerifyRequestData {

    /**
     * 校验body
     *
     * @param body 入参body
     */
    public static void verifyBody(String body) {
        if (StringUtils.isEmpty(body)) {
            log.error("接收到请求： 错误信息:{}", "body为空");
            throw new ServerException(RequestEnum.body.getMessage());
        }
    }

    /**
     * 校验版本号
     *
     * @param version 入参版本号
     */
    public static void verifyVersion(String version) {
        if (StringUtils.isEmpty(version)) {
            log.error("接收到请求： 错误信息:{}", "version为空");
            throw new ServerException(RequestEnum.version.getMessage());
        }
    }

    /**
     * 校验 入参的时间
     *
     * @param timestamp System.currentTimeMillis()
     */
    public static void verifyTimestamp(String timestamp) {
        if (StringUtils.isBlank(timestamp)) {
            log.error("接收到请求： 错误信息:{}", RequestEnum.timestamp.getMessage());
            throw new ServerException(RequestEnum.timestamp.getMessage());
        }

        long currentTimeMillis = System.currentTimeMillis();
        long startTime = Long.parseLong(timestamp);
        long subMillis = currentTimeMillis - startTime;

        if (subMillis / Constant.ONE_THOUSAND > Constant.REQUEST_EXPIRE_TIME) {
            log.info("currentTimeMillis: {}, startTime: {}, currentTimeMillis - startTime: {}, 错误信息:{}",
                    currentTimeMillis,
                    startTime,
                    subMillis,
                    Constant.SYS_MSG_EXPIRE);
            throw new ServerException(Constant.SYS_MSG_EXPIRE);
        }
    }

    /**
     * 解密
     *
     * @param body 密文消息
     * @return 返回明文
     */
    public static String decryptBody(String body) {
        try {
            String decrypt = RSAUtils.decryptByPrivateKey(body, Constant.PRIVATE_KEY);
            if (StringUtils.isEmpty(decrypt)) {
                log.error("接收到请求：错误信息:{}", "解签失败");
                throw new ServerException("解签失败！");
            }
            return decrypt;
        } catch (Exception ex) {
            log.error("接收到请求：错误信息:{}", "解签失败");
            throw new ServerException("解签失败！");
        }
    }
}
